/* eslint-disable react/prop-types */
/* eslint-disable no-console */
/* eslint-disable no-param-reassign */
import React from 'react';
import ReactDom from 'react-dom';
import PropTypes from 'prop-types';
import utils from 'utils';
import { Button, Message, Balloon, Dropdown, TeamixTypography, Divider } from '@teamix/ui';
import CopyToClipboard from 'react-copy-to-clipboard';
import {
  getCommitInfoById,
  getDiffs,
  getBranchAndTag,
  getCommentListByCommitId,
  postComment,
  getCommitsBuilds,
} from 'api';
import TextAvatar from '@txdfe/at-text-avatar';
import { navigate, HrefLink } from 'utils/router';
import CommitIdAndSrcBtns from '../commitIdAndSrcBtns';
import SrcBtn from '../commitIdAndSrcBtns/srcBtn';
import ListLoading from 'atComponents/ListLoading';
import CONSTANTS from 'utils/constants';
import TreeAndDiff from 'components/treeAndDiff';
import { YunxiaoIcon } from '@alife/devops-ui';
// import MoreInfoPanel from './detail';
import './index.scss';
import BuildsResultTag from 'components/buildsResultTag';
import BuildResultDialog from 'components/buildResultDialog/loadable';
import track, { enterModal, Perf } from 'utils/track';
import CherryPickModal from './cherryPickModal';
import RevertModal from './revertModal';
import CreateCRModal from 'components/createCRModal/loadable';
import GpgTag from 'components/gpgTag';
import exceed from 'utils/apimap';
import intl from '../../locale';

const { Text } = TeamixTypography;

const { pathResource, resourceSubject } = window.FORCE;

export default class CommitDetail extends React.Component {
  static propTypes = {
    projectInfo: PropTypes.object,
    commitId: PropTypes.string,
    container: PropTypes.node,
    scanResult: PropTypes.string,
    // url中含show_build弹出该详情
    showBuildId: PropTypes.string,
  };

  static defaultProps = {
    projectInfo: {},
    commitId: '',
    container: null,
    scanResult: '',
    showBuildId: '',
  };

  div = document.createElement('div');

  constructor(props) {
    super(props);
    this.state = {
      curCommitInfo: {},
      isLoadingCommitInfo: true,
      isLoadingDiff: true,
      diffs: [],
      commentList: [],
      tags: [],
      branches: [],
      isShowAllDes: false,
      // isShowMoreInfoPanel: false,
      style: {},
      // url参数中 show_build有：显示该弹窗
      showBuidlResultVisible: !!props.showBuildId,
      showBuidlResult: null,
      isCherryPickOpen: false,
      createMrModalOpen: false,
      // 点击cherry-pick新建出来的源分支
      sourceBranch: '',
      targetBranch: '',
      crType: '',
      // diff 接口错误信息
      errorInfo: '',
      idLink: [],
    };
  }

  closeDialog = () => {
    this.setState({
      showBuidlResultVisible: false,
      showBuidlResult: null,
    });
  };

  componentDidMount() {
    if (!this.props.commitId) {
      return;
    }

    if (this.props.container) {
      this.props.container.appendChild(this.div);
    }
    this.getCommitInfoAndDiffs();
    this.getBranchAndTagInfo();
    this.getCommentList();
    this.props.showBuildId && this.getCurCommitScanBuilds();

    enterModal('Modal-Commit', {
      sendPerf: false,
    });
  }

  componentWillUnmount() {
    if (this.props.container) {
      this.props.container.removeChild(this.div);
    }
  }

  // 在组的概览中pathResource不对
  getRepoFullPath = () => {
    const { repoUrl } = this.props;
    const fullPath = repoUrl ? repoUrl.replace(`${window.location.origin}/`, '') : '';
    return fullPath || pathResource.fullPath;
  };

  // 获取评论
  getCommentList = () => {
    const { commitId, projectId } = this.props;
    const params = { sha: commitId };
    getCommentListByCommitId(params, projectId)
      .then((result) => {
        this.setState({
          commentList: result.slice(1),
        });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  // 提价评论
  postInfo = (params, callback) => {
    const { projectId } = this.props;
    const { submitting } = this.state;
    if (submitting) {
      return;
    }
    this.setState({
      submitting: true,
    });

    postComment(params, projectId)
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.components.commitDetail.CommentsSuccessful',
            defaultMessage: '评论成功',
          }),
        });

        this.setState({
          submitting: false,
        });

        this.getCommentList();
        callback();
      })
      .catch((err) => {
        Message.error({
          title: intl.get({
            id: 'code-assets.components.commitDetail.UnableToComment',
            defaultMessage: '评论失败',
          }),
        });

        this.setState({
          submitting: false,
        });
        // 评论区底部的提交评论按钮或者快捷键提交，埋点
        track({
          action: 'submit_comments',
          page: 'Repo-Commit',
          type: '',
          control: '',
        });
        console.error(err);
      });
  };

  changeTags = (tagInfo) => {
    const { tags } = this.state;
    if (!tags) {
      return;
    }
    this.setState({
      tags: [...tags, { name: tagInfo.name, message: tagInfo.message }],
    });
  };

  getBranchAndTagInfo = (parentId) => {
    const { commitId, projectId } = this.props;
    const params = { sha: parentId || commitId };
    getBranchAndTag(params, projectId)
      .then((result) => {
        this.setState({
          branches: result.branches,
          tags: result.tags,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  getCommitInfoAndDiffs = (parentId) => {
    const { commitId, projectId } = this.props;
    const { isLoadingCommitInfo, isLoadingDiff } = this.state;
    const params = { sha: parentId || commitId, show_signature: true };
    if (!isLoadingCommitInfo || !isLoadingDiff) {
      this.setState({
        isLoadingCommitInfo: true,
        isLoadingDiff: true,
      });
    }
    getCommitInfoById(params, projectId)
      .then((curCommitInfo) => {
        this.setState({
          curCommitInfo,
          isLoadingCommitInfo: false,
        });
        const commitMessage = curCommitInfo.message || curCommitInfo.title || '';
        const [, ...commitMessageDesc] = this.splitCommitMessage(commitMessage);
        this.commitMessageDescHander(commitMessageDesc);
      })
      .catch(() => {
        this.setState({
          isLoadingCommitInfo: false,
        });
      });
    getDiffs(params, projectId)
      .then((result) => {
        const diffs = result.slice(1);
        diffs.forEach((item) => {
          // 添加假的diff头部，此处 0299f74..23f1202 接口中没有，先写死了
          const fakeHeader = `diff --git a/${item.old_path} b/${item.new_path}\nindex 0299f74..23f1202 ${item.b_mode}\n`;
          item.diff = fakeHeader + item.diff;

          // 如果单个diff大小大于 MAX_CR_DIFF_SIZE 或 全部diff数量大于 MAX_DIFF_NUM，则不自动加载内容，让用户手动点击加载
          if (
            item.diff.length > CONSTANTS.MAX_CR_DIFF_SIZE ||
            diffs.length > CONSTANTS.MAX_DIFF_NUM
          ) {
            item.originalDiff = item.diff;
            item.diff = '$WAITING_FOR_CLICK_BIG_SIZE$';
          }
        });
        this.setState({
          diffs,
          isLoadingDiff: false,
        });
      })
      .catch((response) => {
        let errorInfo = '';
        try {
          const responseText = JSON.parse(response.responseText);
          errorInfo = responseText.message || responseText.errorCode;
        } catch (e) {
          errorInfo = intl.get({
            id: 'code-assets.components.commitDetail.TheSystemIsBusyPlease',
            defaultMessage: '系统繁忙，请稍后重试',
          });
        }
        this.setState({
          isLoadingDiff: false,
          errorInfo,
        });
      });
  };

  commitMessageDescHander = (data) => {
    let str = '';
    data.length > 0 &&
      data.map((va) => {
        for (let i = 0, num = Infinity; i < va.length; i++) {
          if (va[i] === '#') {
            num = i;
            str += ',';
          } else if (i > num) {
            str += va[i];
          }
        }
        return va;
      });
    // 提取与#拼接的值，并去重，同时限制并发请求数量 <= 50
    let strData = null;
    if (str && str.length > 0) {
      const temp = {};
      strData = str
        .split(',')
        .filter((val) => {
          if (val) {
            if (temp[val]) return false;
            temp[val] = 1;
            return true;
          }
          return false;
        })
        .slice(0, 50);
    }
    this.commitIdHerfHander(strData);
  };

  commitIdHerfHander = async (data) => {
    if (!data) return false;
    const allRequest =
      data &&
      data.length > 0 &&
      data.map(async (va) => {
        const res = await exceed.fetch({
          api: 'project_commit_info_media_id_herf',
          params: { idList: va },
        });
        return res;
      });
    const result = await Promise.all(allRequest);

    const value = data.map((va, ids) => {
      return { id: va, data: result[ids].result };
    });
    this.setState({
      idLink: value,
    });
  };

  handleChange = (value, type) => {
    this.setState({
      [type]: value,
    });
  };

  clickParentId = (e, item) => {
    e.stopPropagation();
    // 刷新数据
    this.getCommitInfoAndDiffs(item);
    this.getBranchAndTagInfo(item);
  };

  computeParentIds = (data) => {
    if (!data) {
      return [];
    }
    return data.map((item) => (
      <a
        onClick={(e) => {
          this.clickParentId(e, item);
        }}
        key={item}
      >
        {item.substr(0, 8)}
      </a>
    ));
  };

  computebranches = (data) => {
    return data.map((item) => {
      return (
        <HrefLink
          className="commit-detail-brach-single-tag-link"
          href={`/${this.getRepoFullPath()}/tree/${item}`}
          target="blank"
        >
          <Text style={{ maxWidth: 78 }} ellipsis={{ tooltip: item }}>
            {item}
          </Text>
        </HrefLink>
      );
    });
  };

  computeTags = (data) => {
    return data.map((item) => {
      return (
        <HrefLink
          className="commit-detail-brach-single-tag-link"
          href={`/${pathResource.fullPath}/tree/${utils.revisionEncodeURI(item)}`}
          target="blank"
        >
          <Text style={{ maxWidth: 78 }} ellipsis={{ tooltip: item }}>
            {item}
          </Text>
        </HrefLink>
      );
    });
  };

  getCurCommitScanBuilds = () => {
    const { commitId, showBuildId, projectId } = this.props;
    getCommitsBuilds(commitId, projectId)
      .then((result) => {
        result.shift();
        const showBuidlResult =
          (result.length &&
            result.find((item) => {
              return Number(item.id) === Number(showBuildId);
            })) ||
          null;
        this.setState({
          showBuidlResult,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

  getCommitHref = () => {
    return `${window.location.origin}/${this.getRepoFullPath()}/commit/${this.props.commitId}`;
  };

  idlinkHander = (data) => {
    const { idLink } = this.state;
    const resArr =
      Array.isArray(data) &&
      data.length > 0 &&
      data.map((item) => {
        const splitArr = item.split(' ');
        return splitArr.map((v) => {
          if (v.indexOf('#') === -1) return v;
          const urlSplit = v.split('#');
          for (let i = 1; i < urlSplit.length; i += 1) {
            const flag =
              Array.isArray(idLink) &&
              idLink.length > 0 &&
              idLink.find((va) => va.id === urlSplit[i]);
            if (flag && flag.data?.length > 0) {
              urlSplit[i] = (
                <a
                  href={`${window.config.tbHost}/task/${flag.data[0]._id}`}
                  target="_blank"
                  rel="noreferrer"
                  style={{ paddingRight: 5 }}
                >
                  #{urlSplit[i]}
                </a>
              );
            } else {
              urlSplit[i] = <span>#{urlSplit[i]}</span>;
            }
          }
          return urlSplit;
        });
      });
    return (
      <div className="commit-msg-desc">
        {Array.isArray(resArr) &&
          resArr.map((v) => {
            return (
              <div className="commit-msg-desc-item" style={{ marginRight: '3px' }}>
                {v.map((va) => (
                  <span style={{ marginRight: '4px' }}>{va}</span>
                ))}
              </div>
            );
          })}
      </div>
    );
  };

  splitCommitMessage = (message) => {
    const commitMessageArr = message.split('\n');
    return commitMessageArr;
  };

  // 点击展开更多时，埋点
  onClickMoreTrack = () => {
    track({
      action: 'view_more',
      page: 'Repo-Commit',
      type: '',
      control: '',
    });
  };

  // 点击后退按钮时，埋点
  onClickBackNavigation = () => {
    // FIXME 返回上一页，行为待商榷
    typeof window.history !== 'undefined' && window.history.back();
    track({
      action: 'return_previous_page',
      page: 'Repo-Commit',
      type: '',
      control: '',
    });
  };

  renderHeader = () => {
    const { curCommitInfo, isShowAllDes } = this.state;
    const user_info = curCommitInfo.user || curCommitInfo.author || '';
    const user_name = user_info ? user_info.name || user_info.username : curCommitInfo.author_name;
    const commitMessage = curCommitInfo.message || curCommitInfo.title || '';
    const [commitMessageTitle, ...commitMessageDesc] = this.splitCommitMessage(commitMessage);
    // 去除空行
    const commitMessageDescNotEmpty = commitMessageDesc.filter((item) => {
      return item.trim() !== '';
    });

    const curCommitMsgDes = isShowAllDes
      ? commitMessageDescNotEmpty
      : commitMessageDescNotEmpty.slice(0, 3);
    // 作者和提交者不一致时，都显示出来
    const author_committer = [
      {
        avatar_url: user_info.avatar_url || '',
        name: user_name || '',
        date: curCommitInfo.authored_date || '',
        is_autor: true,
      },
    ];

    if (user_info && curCommitInfo.author_email !== curCommitInfo.committer_email) {
      author_committer.push({
        avatar_url: curCommitInfo.committer.avatar_url || '',
        name:
          curCommitInfo.committer.name ||
          curCommitInfo.committer.username ||
          curCommitInfo.committer_name ||
          '',
        date: curCommitInfo.created_at || '',
      });
    }

    const author_committer_jsx = author_committer.map((item, index) => {
      return (
        <div className="user-action-time" style={{ marginLeft: index > 0 ? 16 : 0 }}>
          <TextAvatar
            text={item.name}
            image={item.avatar_url}
            size="xs"
            radius="50%"
            needAddedText
          />
          {author_committer.length > 1 && item.is_autor ? (
            <span className="user-action-time-add-text-autor">（作者）</span>
          ) : null}
          <div className="user-action-des">
            {index > 0
              ? intl.get({
                  id: 'code-assets.components.commitDetail.Submitted',
                  defaultMessage: '提交于',
                })
              : intl.get({
                  id: 'code-assets.components.commitDetail.CreatedOn',
                  defaultMessage: '创建于',
                })}
            {utils.getBeautyTime(item.date).toLowerCase()}
          </div>
        </div>
      );
    });

    const { projectInfo } = this.props;

    const buildsResultAndAuthorInfo = [
      author_committer_jsx,
      curCommitInfo.id ? (
        <div className="scan-result">
          <BuildsResultTag
            container={{
              target: 'commit', // 可选值为 commit 和 merge_request
              id: curCommitInfo.id, // commit 或 merge_request 的 id
            }}
            projectInfo={projectInfo}
          />
        </div>
      ) : null,
    ];

    const moreBtn = [
      <SrcBtn
        commitInfo={curCommitInfo}
        pathResource={pathResource}
        onClick={() => {
          const url = `/${this.getRepoFullPath()}/tree/${curCommitInfo.id}`;
          //  commit 改造
          navigate(url, {
            state: { forceUpdate: true },
          });

          track({
            action: 'view_commit_source_file',
            page: 'Modal-Commit',
            type: '',
            control: 'navigation',
          });
        }}
      />,

      <Dropdown
        trigger={
          <Button style={{ marginLeft: 8, marginRight: 4 }}>
            <YunxiaoIcon type="more-line" />
          </Button>
        }
        triggerType="click"
        align="tr br"
        followTrigger
      >
        <div className="more-btn-dropdown-content overlay-shadow">
          <div>
            <Button
              type="normal"
              component="a"
              color="gray"
              onClick={() => {
                track({
                  action: 'compare_commits',
                  page: 'Modal-Commit',
                  type: '',
                  control: '',
                });

                navigate(
                  `/${this.getRepoFullPath()}/compare?from=${encodeURIComponent(
                    this.props.commitId,
                  )}&to=${encodeURIComponent(pathResource.defaultBranch)}${
                    resourceSubject.subject
                      ? `&tab=${encodeURIComponent(resourceSubject.subject)}`
                      : ''
                  }`,
                  { state: { forceUpdate: true } },
                );
              }}
              text
            >
              {intl.get({
                id: 'code-assets.components.commitDetail.Comparison',
                defaultMessage: '比较',
              })}
            </Button>
          </div>
          <div>
            <Button
              type="normal"
              component="a"
              color="gray"
              onClick={() => {
                this.setState({
                  isRevertOpen: true,
                });
              }}
              text
            >
              Revert
            </Button>
          </div>
          <div>
            <Button
              type="normal"
              component="a"
              color="gray"
              onClick={() => {
                this.setState({
                  isCherryPickOpen: true,
                });
              }}
              text
            >
              Cherry-pick
            </Button>
          </div>
        </div>
      </Dropdown>,
    ];

    return (
      <div className="commit-detail-header">
        <div className="commit-detail-header-title">
          <div className="commit-detail-header-title-left">
            <Balloon.Tooltip
              trigger={
                <Button text size="small" style={{ marginRight: -3 }}>
                  <YunxiaoIcon type="arrow-left-line" onClick={this.onClickBackNavigation} />
                </Button>
              }
            >
              后退
            </Balloon.Tooltip>
            <Divider direction="ver" style={{ marginLeft: 12, marginRight: 12 }} />
            <Balloon.Tooltip
              trigger={<div className="msg-title one-line-ellipsis">{commitMessageTitle}</div>}
              align="b"
            >
              {commitMessageTitle}
            </Balloon.Tooltip>
          </div>
          <div className="commit-detail-header-title-right">
            <div style={{ marginRight: 8 }}>
              <GpgTag
                signature={curCommitInfo.signature}
                author={{
                  name: user_name || '',
                  avatarUrl: user_info.avatar_url || '',
                }}
              />
            </div>
            <div className="commit-detail-header-title-right-context">
              <div className="commit-id-src-group">
                <CommitIdAndSrcBtns
                  {...{
                    commitInfo: curCommitInfo,
                    pathResource,
                    isSrcBtnShow: false,
                    isCommitIdCursorDefault: true,
                  }}
                />
              </div>
              <div className="more-btn">{moreBtn}</div>
              <Dropdown
                trigger={
                  <Button
                    onClick={this.onClickMoreTrack}
                    className="more-btn-dropdown-trigger"
                    style={{ marginLeft: 20 }}
                  >
                    <YunxiaoIcon type="more-line" />
                  </Button>
                }
                triggerType="click"
                align="tr br"
                followTrigger
              >
                <div className="more-btn-dropdown-content overlay-shadow">
                  <div>
                    <Button
                      type="normal"
                      component="a"
                      color="gray"
                      onClick={() => {
                        track({
                          action: 'compare_commits',
                          page: 'Modal-Commit',
                          type: '',
                          control: '',
                        });

                        navigate(
                          `/${this.getRepoFullPath()}/compare?from=${encodeURIComponent(
                            this.props.commitId,
                          )}&to=${encodeURIComponent(pathResource.defaultBranch)}${
                            resourceSubject.subject
                              ? `&tab=${encodeURIComponent(resourceSubject.subject)}`
                              : ''
                          }`,
                          { state: { forceUpdate: true } },
                        );
                      }}
                      text
                    >
                      {intl.get({
                        id: 'code-assets.components.commitDetail.Comparison',
                        defaultMessage: '比较',
                      })}
                    </Button>
                  </div>
                  <div>
                    <CopyToClipboard
                      text={this.getCommitHref()}
                      onCopy={() => {
                        track({
                          action: 'copy_commit_link',
                          page: 'Modal-Commit',
                          type: '',
                          control: '',
                        });

                        Message.success({
                          title: intl.get({
                            id: 'code-assets.components.commitDetail.CopiedSuccessfully',
                            defaultMessage: '复制成功',
                          }),
                        });
                      }}
                    >
                      <Button type="normal" color="gray" text component="a">
                        {intl.get({
                          id: 'code-assets.components.commitDetail.CopyLink',
                          defaultMessage: '复制链接',
                        })}
                      </Button>
                    </CopyToClipboard>
                  </div>
                  <div>
                    <Button
                      type="normal"
                      component="a"
                      color="gray"
                      onClick={() => {
                        const url = `/${this.getRepoFullPath()}/tree/${curCommitInfo.id}`;
                        navigate(url, {
                          state: { forceUpdate: true },
                        });

                        track({
                          action: 'view_commit_source_file',
                          page: 'Modal-Commit',
                          type: '',
                          control: 'navigation',
                        });
                      }}
                      text
                    >
                      {intl.get({
                        id: 'code-assets.components.commitDetail.ViewSourceFiles',
                        defaultMessage: '查看源文件',
                      })}
                    </Button>
                  </div>
                  <div>
                    <Button
                      type="normal"
                      component="a"
                      color="gray"
                      onClick={() => {
                        this.setState({
                          isRevertOpen: true,
                        });
                      }}
                      text
                    >
                      Revert
                    </Button>
                  </div>
                  <div>
                    <Button
                      type="normal"
                      component="a"
                      color="gray"
                      onClick={() => {
                        this.setState({
                          isCherryPickOpen: true,
                        });
                      }}
                      text
                    >
                      Cherry-pick
                    </Button>
                  </div>
                </div>
              </Dropdown>
            </div>
          </div>
        </div>
        <div className="commit-detail-author-list">
          <div className="builds-and-author">{buildsResultAndAuthorInfo}</div>
        </div>
        <div className="commit-detail-des">
          {commitMessageDescNotEmpty.length > 0 ? (
            <pre className="commit-detail-des-pre">
              {curCommitMsgDes ? this.idlinkHander(curCommitMsgDes) : null}
            </pre>
          ) : null}
        </div>
        <div
          className="toggle-all-des-btn"
          style={{ display: commitMessageDescNotEmpty.length > 3 ? 'block' : 'none' }}
        >
          <Button
            type="primary"
            size="small"
            text
            onClick={() => {
              this.setState({ isShowAllDes: !isShowAllDes });
            }}
            style={{ fontSize: 12 }}
          >
            {isShowAllDes
              ? intl.get({
                  id: 'code-assets.components.commitDetail.PutAway',
                  defaultMessage: '收起',
                })
              : intl.get({
                  id: 'code-assets.components.commitDetail.Expand',
                  defaultMessage: '展开',
                })}
            <YunxiaoIcon type={isShowAllDes ? 'arrow-up-2-line' : 'arrow-down-2-line'} />
          </Button>
        </div>
      </div>
    );
  };

  renderBody = () => {
    const { commitId, genWatermarkimage } = this.props;
    const {
      diffs,
      curCommitInfo,
      commentList,
      isLoadingDiff,
      errorInfo,
      branches,
      tags,
      isShowAllDes,
    } = this.state;

    return (
      <TreeAndDiff
        commitId={commitId}
        diffs={diffs}
        curCommitInfo={curCommitInfo}
        commentList={commentList}
        onChange={this.handleChange}
        loading={isLoadingDiff}
        isInCommitDetail
        errorInfo={errorInfo}
        genWatermarkimage={genWatermarkimage}
        changeTags={this.changeTags}
        branches={branches}
        tags={tags}
        computebranches={this.computebranches}
        computeTags={this.computeTags}
        computeParentIds={this.computeParentIds}
        postInfo={this.postInfo}
        isShowAllDes={isShowAllDes}
        isNewCommitOnchange
        associatePanelOptions={this.props.associatePanelOptions}
      />
    );
  };

  myRender = () => {
    if (!this.props.commitId) {
      return null;
    }
    const { projectId, branchName } = this.props;
    const {
      isLoadingCommitInfo,
      isLoadingDiff,
      // branches,
      // tags,
      curCommitInfo,
      // commentList,
      showBuidlResultVisible,
      showBuidlResult,
      isCherryPickOpen,
      createMrModalOpen,
      sourceBranch,
      targetBranch,
      crType,
      isRevertOpen,
    } = this.state;
    const pageStyle =
      this.props.style && this.props.style.zIndex
        ? { zIndex: this.props.style.zIndex, ...this.state.style }
        : this.state.style;
    return (
      <React.Fragment>
        <div className="commit-detail-page" style={pageStyle}>
          {isLoadingCommitInfo || isLoadingDiff ? (
            <div className="loading-box">
              <ListLoading />
            </div>
          ) : (
            [
              this.renderHeader(),
              this.renderBody(),
              <Perf page={'Modal-Commit'} pathname={this.getCommitHref()} />,
            ]
          )}

          {showBuidlResultVisible && showBuidlResult && (
            <BuildResultDialog
              build={showBuidlResult}
              close={this.closeDialog}
              projectId={this.props.projectId}
            />
          )}
        </div>
        {isCherryPickOpen && (
          <CherryPickModal
            isModalOpen={isCherryPickOpen}
            onClose={() => {
              this.setState({
                isCherryPickOpen: false,
              });
            }}
            projectId={projectId || window.FORCE.pathResource.id}
            sha={this.props.commitId}
            onChange={(data) => {
              this.setState({
                ...data,
                crType: 'cherry-pick',
              });
            }}
          />
        )}

        {isRevertOpen && (
          <RevertModal
            isModalOpen={isRevertOpen}
            onClose={() => {
              this.setState({
                isRevertOpen: false,
              });
            }}
            branchName={branchName || (resourceSubject ? resourceSubject.revision : '')}
            projectId={projectId || window.FORCE.pathResource.id}
            sha={this.props.commitId}
            onChange={(data) => {
              this.setState({
                ...data,
                crType: 'revert',
              });
            }}
          />
        )}

        {createMrModalOpen && (
          <CreateCRModal
            cannotChangeProject
            isModalOpen={createMrModalOpen}
            defaultProjectId={projectId || window.FORCE.pathResource.id}
            defaultSourceBranch={sourceBranch}
            defaultTargetBranch={targetBranch}
            isCherryPick
            title={
              crType === 'cherry-pick'
                ? `Cherry-pick "${curCommitInfo.message}"`
                : `Revert "${curCommitInfo.message}"`
            }
            desc={
              crType === 'cherry-pick'
                ? intl.get(
                    {
                      id: 'code-assets.components.commitDetail.CherryPickSubmitCurcommitinfoid',
                      defaultMessage: 'Cherry-pick 提交 {curCommitInfoId}',
                    },
                    { curCommitInfoId: curCommitInfo.id },
                  )
                : intl.get(
                    {
                      id: 'code-assets.components.commitDetail.RestoreAndSubmitCurcommitinfoid',
                      defaultMessage: '还原提交 {curCommitInfoId}',
                    },
                    { curCommitInfoId: curCommitInfo.id },
                  )
            }
            onCloseModal={() => {
              this.setState({ createMrModalOpen: false, isCherryPickOpen: false });
            }}
          />
        )}
      </React.Fragment>
    );
  };

  render() {
    if (this.props.container) {
      return ReactDom.createPortal(this.myRender(), this.div);
    }
    return this.myRender();
  }
}
